package com.jp.knowledge.my.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.adapter.VipGradeAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PayLogic;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.VipGrade;
import com.jp.knowledge.my.adapter.PayWayAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.PayWayModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;
import com.jp.knowledge.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/5/8.
 */

public class VipBuyActivity extends SlidingActivity implements View.OnClickListener, ResultSubscriber.OnResultListener {

    @ViewInject(R.id.vip_should_pay_money)
    private TextView vipShouldPayMoney;
    @ViewInject(R.id.vip_sure_pay_btn)
    private TextView vipSurePayBtn;
    @ViewInject(R.id.list_view)
    private RecyclerView listView;
    @ViewInject(R.id.pay_way_list_view)
    private RecyclerView payWayListView;
    @ViewInject(R.id.pay_prompt)
    private TextView payPrompt;

    protected List<VipGrade> list;
    protected List<PayWayModel> payWayModelList;
    protected VipGradeAdapter adapter;
    protected PayWayAdapter payWayAdapter;
    protected VipGrade curVipGrade;
    protected PayLogic payLogic;
    protected LocalBroadCast localBroadCast;
    protected LocalBroadcastManager localBroadcastManager;

    private String title;
    private String gradesId;

    @Override
    protected int getResourceId() {
        return R.layout.activity_user_vip_buy;
    }

    @Override
    protected void init() {
        payLogic = new PayLogic(mContext);
        list = new ArrayList<>();
        payWayModelList = new ArrayList<>();

        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        gradesId = intent.getStringExtra("gradesId");
        if(gradesId == null)
            gradesId = "UL02";

        initTitleBar();
        initBroadcase();

        vipSurePayBtn.setOnClickListener(this);
        adapter = new VipGradeAdapter(mContext,list);
        listView.setHasFixedSize(true);
        listView.addItemDecoration(new JpDiver(mContext));
        listView.setLayoutManager(new LinearLayoutManager(mContext){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        listView.setAdapter(adapter);
        adapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                if(position == adapter.getSelectedPosition() || position < 0 || position > list.size()-1)
                    return;
                adapter.setSelectedPosition(position);
                adapter.updateAdapter(list);
                curVipGrade = list.get(position);
                setVipPrice();
            }
        });

        payWayListView.setHasFixedSize(true);
        payWayListView.addItemDecoration(new JpDiver(mContext));
        payWayListView.setLayoutManager(new LinearLayoutManager(mContext){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        payWayAdapter = new PayWayAdapter(mContext, payWayModelList);
        payWayListView.setAdapter(payWayAdapter);
        payWayAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                if(position == payWayAdapter.getSelectIndex() || position < 0 || position > payWayModelList.size()-1)
                    return;
                payWayAdapter.setSelectIndex(position);
                payWayAdapter.notifyDataSetChanged();
            }
        });

        getData();//获取套餐数据
        getPayWayData();
    }

    protected void initTitleBar(){
        rightIcon.setVisibility(View.GONE);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setOnClickListener(this);
        topName.setText(title == null ? "购买VIP会员" : title);
    }

    private void initBroadcase(){
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                onPayFinish(context, intent);
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WXPayEntryActivity.WECHAT_PAY);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    protected void onPayFinish(Context context, Intent intent){
        String action = intent.getAction();
        if(WXPayEntryActivity.WECHAT_PAY.equals(action)){
            int errCode = intent.getIntExtra(WXPayEntryActivity.WECHAT_PAY_ERR_CODE, -1);
            // 支付成功刷新用户数据
            if(errCode == BaseResp.ErrCode.ERR_OK) {
                new PersonLogic(mContext).getUserData();
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        super.onDestroy();
    }

    protected void setVipPrice(){
        if(curVipGrade != null)
            vipShouldPayMoney.setText("￥" + String.format("%.2f", curVipGrade.getPackagePrice()/100.00));
    }

    protected void getData() {
        JsonObject param = new JsonObject();
        param.addProperty("gradesId",gradesId);
        HttpHelper.getInstance(mContext).gradesPackage(param, 1, this);
    }

    protected void getPayWayData(){
        HttpHelper.getInstance(mContext).getPayWay(new JsonObject(), 2, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.vip_sure_pay_btn://调起微信支付开始付款
                if(curVipGrade == null)
                    ToasUtil.toast(mContext, "获取不到套餐");
                else if(payWayAdapter.getSelectIndex() < 0 || payWayAdapter.getSelectIndex() >= payWayModelList.size())
                    ToasUtil.toast(mContext, "请选择支付方式");
                else if(!"WECHATPAY".equals(payWayModelList.get(payWayAdapter.getSelectIndex()).getMethod()))
                    ToasUtil.toast(mContext, "目前暂时只支持微信支付，请选择微信支付");
                else
                    openWeChatPay(curVipGrade.getPackagePrice());
                break;
        }
    }

    protected void openWeChatPay(int money){
        payLogic.pay(money,application.getUserData().getUuid(),"00000000",24,"购买会员",1010,curVipGrade.getPackageId());
    }

    @Override
    public void onStart(int requestType) {
        loading.show();
    }
    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == 1){
            list = data.getList(VipGrade.class);
            adapter.setSelectedPosition(0);
            curVipGrade = list.get(0);
            setVipPrice();
            adapter.updateAdapter(list);
        } else if(requestType == 2){
            payWayModelList = data.getList(PayWayModel.class);
            payWayAdapter.setSelectIndex(0);
            payWayAdapter.updateAdapter(payWayModelList);
            if(payWayModelList == null && payWayModelList.size() == 0)
                return;
            List<PayWayModel.PromptBean> promptBeen = payWayModelList.get(0).getPrompt();
            if(promptBeen == null || promptBeen.size() == 0)
                return;
            String prompt = "";
            for(int i = 0, j = promptBeen.size(); i < j; i++)
                prompt += (promptBeen.get(i).getTitle() + "\n");
            payPrompt.setText(prompt);
        }
    }
}
